<?php

namespace app\admin\controller\material;

use app\common\model\SystemGoods;
use app\common\model\SystemGoodsDetail;
use library\Controller;
use think\Db;
use library\File;

/**
 * 制版素材管理
 * Class Product
 * @package app\admin\controller\material
 */
class Platematerial extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SystemMaterial';

    /**
     * 素材列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '制版素材管理';
        $this->shop_op = assemble_op([''=>'-- 全部店铺 --'], get_all_shop());
        $where = [];       
        $where[] = ['is_deleted','eq',0]; 
        $status = $this->request->get('status'); 
        if($status){
        	$where[] = ['status','eq',$status];    
        }
        
        $query = $this->_query($this->table)->like('code,name')->equal('shop_id');
        $query->where($where)->dateBetween('create_at,update_at')->order('sort desc,id asc')->page();
    }
    
    
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {  	
    	foreach($data as $vo){
    		$ids[] = $vo['id'];
    	}
		if(!empty($ids) && $ids){
			$shops = get_all_shop();
	        foreach ($data as &$vo) {       	
	        	$vo['shop_name'] = $shops[$vo['shop_id']] ?? '';    
	        }
		}
    }


    /**
     * 添加素材
     * @auth true
     */
    public function add()
    {
    	$this->shop_op = get_all_shop();
        $this->_form($this->table, 'form');
    }

    


    /**
     * 表单数据后置处理
     * @param number $id
     * @auth true
     */
    protected function _add_form_result($id)
    {
        $info = Db::name($this->table)->where(['id' => $id])->find();
        if ($info) {
            sysoplog('制版素材管理', '添加' . $info['name'] . '成功');
            $this->success('保存成功');
        }

    }

    /**
     * 更新
     * @auth true
     */
    public function edit()
	{
		if($this->request->isPost()){
			$data = $this->request->post();	
			
			if(!$data['annex_url'] || !$data['annex_name']){
        		$this->error('附件必须上传');
        	}
        	
        	$arr = [
        		'thumb_img' => $data['thumb_img'],
        		'annex_url' => $data['annex_url'],
        		'annex_name' => $data['annex_name'],
        		'shop_id' => $data['shop_id'],
        		'desc' => $data['desc'],
        	];
        	$re = Db::name($this->table)->where(['id'=>$data['id']])->update($data);
        	if($re){
        		$this->success('更新成功');
        	}else{
        		$this->error('更新失败，请稍后再试');
        	}
		}else{
			$id = $this->request->param('id');
			if(empty($id) || !$id){
				$this->error('参数错误');
			}
			$this->id = $id;
			$info = Db::name($this->table)->where(['id'=>$id])->find();
			$this->info = $info;						   	      	  
		}
		$this->shop_op = get_all_shop();
		$this->fetch('edit'); 
	}

	/**
     * 图片上传
     */
    public function image_upload()
    {
        $image = request()->file('image');
        
        $uptype = sysconf('storage_type');
        if(in_array($uptype,['oss', 'qiniu', 'cos'])){
        	$extend = pathinfo($image->getInfo('name'), PATHINFO_EXTENSION);       
	        $name = File::name($image->getPathname(), $extend, '', 'md5_file');     	
        	$name = explode('/',$name);
			$name = $name[1];
			$name = 'imgs/'.date('Ymd').'/'.$name;
			$info = File::instance($uptype)->save($name, file_get_contents($image->getRealPath()), false);
			if (is_array($info) && isset($info['url'])) {
	            $this->success('',$info['url']);
	       } else {
	            // 上传失败获取错误信息
	            $this->error('文件处理失败，请稍候再试！');
	        }
        }else{
        	$info = $image->move('upload');
	        if ($info) {
	            $this->success('',str_replace('\\','/','/upload/'.$info->getSaveName()));
	        } else {
	            // 上传失败获取错误信息
	            $this->error($image->getError());
	        }
        }
    }
    
    
    /**
     * 附件上传
     */  
	public function upload(){
	    // 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file('file');	
		if (empty($file) || !$file) {
            $this->error('文件上传异常，文件可能过大或未上传');
       	} 
        if ($file->checkExt('php,sh')) {
            return json(['uploaded' => false, 'error' => ['message' => '可执行文件禁止上传']]);
        }
        if (!$file->checkSize(10485760)) {
            return json(['uploaded' => false, 'error' => ['message' => '文件过大，不能大于10M']]);
        }	
		$path = 'upload/annex/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
		$realName = $file->getInfo()['name'];
	    $info = $file->move($path);
	    if($info){
	        $enclosure = $path.$info->getSaveName();
			$this->success('上传成功',['annex_name'=>$realName,'annex_url'=>$enclosure]);
	    }else{
	        // 上传失败获取错误信息
	        $this->error($file->getError());
	    }
	}


    /**
     * 禁用产品
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '2']);
    }

    /**
     * 启用产品
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }
    
    
    /**
     * 下载
     * @param array $data
     * @auth true
     */
	public function download()
    {
    	$id = $this->request->get('id');
    	$info = Db::name($this->table)->where(['id'=>$id])->find();
		if(!$info){
			$this->error('参数错误');
		}		
		if($info['annex_url']){
			file_download($info['annex_name'],$info['annex_url']);
		}else{
			$this->error('暂无素材附件，无法下载');
		}
    }
    

    /**
     * 删除
     * @auth true
     */
    public function remove()
    {	
        $this->_delete($this->table);
    }
    
    
    /**
	 * 删除结果处理
	 * @param boolean $result
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	protected function _remove_delete_result($result)
	{
	    if ($result) {
	        $id = $this->request->post('id');
	        $info = Db::name($this->table)->where(['id'=>$id])->find();
	        sysoplog('制版素材', '删除'.$info['name'].'成功');
			$this->success('删除成功');
	    } else {
	        $this->error("删除失败，请稍候再试");
	    }
	}

    
}
